package gw.com.android.terminal;

import android.content.res.AssetManager;
import android.text.TextUtils;

import com.gwtsz.chart.output.utils.GTTFormularContent;
import com.gwtsz.chart.output.utils.GTTKDataModel;
import com.gwtsz.chart.output.utils.GTTKDataRequest;
import com.gwtsz.chart.output.utils.GTTTimeDataModel;
import com.gwtsz.chart.output.utils.GTTIndexDataRequest;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;

import gw.com.android.utils.ChannelUtil;
import gw.com.android.utils.ServerConnnectUtil;

import gw.com.jni.library.terminal.GTSConst;
import gw.com.jni.library.terminal.GTSTerminal;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;

/**
 * Created by reeta.zou on 2016/7/29.
 *
 * 统一管理跟jni方法关联管理类
 */
public class AppTerminal {

    private boolean isConnectJni = true;//是否关联jni操作
    private static AppTerminal instance = null;

    public static AppTerminal instance(){
        if (instance == null){
            instance = new AppTerminal();
        }
        return instance;
    }

    /**
     * 初始化跟jni数据沟通对象
     */
    public void initTerminal(String urlStr, String sdPath, AssetManager asset, String listenerPath){
        if(isConnectJni){
            GTSTerminal.instance().initTerminal(urlStr, sdPath, asset, listenerPath);
        }
    }

    /**
     * 跟jni沟通的通知关联对象
     */
    public void addGTSDataListener(){
        if(isConnectJni){
            GTSTerminal.instance().addGTSDataListener(GTSDataListener.instance());
        }
    }

    /**
     * 登录功能
     * @param loginType 登录类型
     * @param name 登录名
     * @param password 登录密码
     * @return
     */
    public int loginFun(int accountType, int loginType, String name, String password){
        if(isConnectJni){
            JSONObject object = new JSONObject();
            try {
                object.put("accountType",accountType);
                object.put("loginType", loginType);
                object.put("account", name);
                object.put("password", password);
                object.put("macStr",  DeviceUtil.instance().getMacAddr(AppMain.getApp()));
                object.put("companyId", ConfigUtil.instance().mConfigObject.optInt(ConfigType.COMPANY_ID_TAG));
                String channelTag = new ChannelUtil().getChannelTag();
                if (!TextUtils.isEmpty(channelTag)){
                    object.put("channel",channelTag);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return GTSTerminal.instance().loginFun(object.toString());
        }

        return 0;
    }


    /**
     * 登出
     */
    public void Logout(int type, int lastID){
        if(isConnectJni){
            GTSTerminal.instance().Logout(type,lastID);
        }
    }

    /**
     * 退出应用程序
     */
    public void exitApp(){
        if(isConnectJni){
            GTSTerminal.instance().exitApp();
        }
    }

    /**
     * 订阅报价
     *
     * @param codes codes内可能包含多个code，code是产品的数字id
     */
    public void sendQuoteSubscribe(ArrayList codes){
        if(isConnectJni && null != codes && ServerConnnectUtil.instance().isQuoteConnect && ServerConnnectUtil.instance().isNetConnect){
            for (int i = 0; i < codes.size();i++){
                DataItemDetail item = DataManager.instance().mTickMap.get(codes.get(i).toString());
                if(null != item){
                    Logger.e("订阅产品：" + item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME) +", " + item.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB) );
                }
            }
            Logger.e("gw.com.android","订阅产品: codeList == " + codes.toString());
            GTSTerminal.instance().sendQuoteSubscribe(codes);
        }else{
            if(!ServerConnnectUtil.instance().isQuoteConnect || !ServerConnnectUtil.instance().isNetConnect){
                DataManager.instance().clearCodes();
            }
        }
    }

    /**
     * 标识界面是否已绘制好,true标识已绘制好，可发送数据通知过来
     * @param isResumed
     */
    public void setViewState(boolean isResumed){
        if(isConnectJni){
            GTSTerminal.instance().setViewState(isResumed);
        }
    }

    /**标识应用是在后台运行还是前台运行，true标识后面，false标识前台*/
    public void setBackRunState(boolean isBackRunning){
        if(isConnectJni){
            GTSTerminal.instance().setBackRunState(isBackRunning);
        }
    }

    /**主动断开服务器连接，type 标识断开哪个服务器*/
    public void onDisconnect(int type){
        if(isConnectJni){
            Logger.e("进入断开服务器方法 onDisconnect 。。。" + type);
            if(type == AppContances.SERVER_TYPE_QUOTE){
                ServerConnnectUtil.instance().autoQuoteConnect = 1;
            }else if(type == AppContances.SERVER_TYPE_QUOTE){
                ServerConnnectUtil.instance().autoTradeConnect = 1;
            }else {
                ServerConnnectUtil.instance().autoQuoteConnect = 1;
                ServerConnnectUtil.instance().autoTradeConnect = 1;
            }
            GTSTerminal.instance().onDisconnect(type);
        }
    }

    /**
     * 是否在登录界面
     * @param isLoginView
     */
    public void setLoginView(int isLoginView){
        if(isConnectJni){
            Logger.e("setLoginView == " + isLoginView);
            GTSTerminal.instance().setLoginView(isLoginView);
        }
    }

    /**重连服务器连接，type 标识重连哪个服务器*/
    public void setReConnect(int type){
        if(isConnectJni){
            Logger.e("进入重连方法 setReConnect 。。。" + type);
            if(NetworkMonitor.hasNetWorkNoToast() && !ServerConnnectUtil.instance().isNetConnect){
                ServerConnnectUtil.instance().isNetConnect = true;
                ServerConnnectUtil.instance().initTimerTask();
                GTSTerminal.instance().setReConnect(type);
                AppTerminal.instance().setNetWorkState(NetworkMonitor.getNetworkType(AppMain.getApp()),true);
            }else{
                if(!ServerConnnectUtil.instance().isReconnect){
                    ServerConnnectUtil.instance().initTimerTask();
                }else{
                    ServerConnnectUtil.instance().connnectFailToast(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1056));
                }
                GTSTerminal.instance().setReConnect(type);
            }
        }
    }

    /**标识网络状态,true标识已连接好,0无,1mobile,2wifi*/
    public void setNetWorkState(int type,boolean isConnect){
        if(isConnectJni){
            GTSTerminal.instance().setNetWorkState(type, isConnect);
        }
    }

    public String  getHotProductList(int uiNum){
        String str = "";
        if(isConnectJni){
            str = GTSTerminal.instance().getHotProductList(uiNum);
        }

        return str;
    }

    public String  searchProductList(String sName){
        String str = "";
        if(isConnectJni){
            str = GTSTerminal.instance().searchProductList(sName);

        }

        return str;
    }

    public int addProductToHistory(int uCode){
        if(isConnectJni){
            return GTSTerminal.instance().addProductToHistory(uCode);
        }

        return 0;
    }

    public String  getAllProductHistory(){
        String str = "";
        if(isConnectJni){
            str = GTSTerminal.instance().getAllProductHistory();
        }

        return str;
    }

    public int removeAllProductHistory(){
        if(isConnectJni){
            return GTSTerminal.instance().removeAllProductHistory();
        }

        return 0;
    }


    /**语言类型设置*/
    public void setLanguage(String type){
        if(isConnectJni){
            GTSTerminal.instance().setLanguage(type);
        }
    }

    /**时区设置*/
    public void setZoneType(int type){
        if(isConnectJni){
            GTSTerminal.instance().setZoneType(type);
        }
    }

    /**获取时区*/
    public int getZoneType(){
        if(isConnectJni){
            return GTSTerminal.instance().getZoneType();
        }

        return 0;
    }

    public String getProtertyModel(int uiCode){
        if(isConnectJni){
            return GTSTerminal.instance().getProtertyModel(uiCode);
        }
        return "";
    }

    public String getMarginLevel(int uiCode){
        if(isConnectJni){
            return GTSTerminal.instance().getMarginLevel(uiCode);
        }
        return "";
    }

    /**下单界面获取到的相关产品*/
    public String getTradeParamModel(int uiCode){
        if(isConnectJni){
            return GTSTerminal.instance().getTradeParamModel(uiCode);
        }
        return "";
    }
    /**
     * 保存自选标识
     * @param uiCode
     */
    public void addSelectStock(int uiCode){
        if(isConnectJni){
            GTSTerminal.instance().addSelectStock(uiCode);
        }
    }

    /**
     * 删除自选标识
     * @param uiCode
     */
    public void delSelectStock(int uiCode){
        if(isConnectJni){
            GTSTerminal.instance().delSelectStock(uiCode);
        }
    }

    /**
     * 通知当前下单产品id
     * @param uiCode
     */
    public void nofityOrder(int uiCode){
        if(isConnectJni){
            GTSTerminal.instance().nofityOrder(uiCode);
        }
    }

    public int reqOrder(int type, String mData){
        Logger.e("reqOrder === " + mData);
        if(isConnectJni){
            int result = GTSTerminal.instance().reqOrder(type,mData);
            Logger.e("reqOrder === " + result);
            return result;
        }
        return 0;
    }

    public void reqOrderCancel(int orderId, int seq){
        if(isConnectJni){
            GTSTerminal.instance().reqOrderCancel(orderId, seq);
        }
    }

    public void saveCustomer(ArrayList codes){
        Logger.e("saveCustomer == " + codes.toString());
        if(isConnectJni){
            GTSTerminal.instance().saveCustomer(codes);
        }
    }

    public void updatePassword(String originalPassword, String newPassword){
        if(isConnectJni){
            GTSTerminal.instance().updatePassword(originalPassword, newPassword);
        }
    }

    public void resetPassword(String accoutid, String email){
        if(isConnectJni){
            GTSTerminal.instance().resetPassword(accoutid, email);
        }
    }

    public void getUpdateVersion(){
        if(isConnectJni){
            GTSTerminal.instance().getUpdateVersion();
        }
    }

    public void getNewsList(String type, int pageSize, int pageNo){
        if(isConnectJni){
            GTSTerminal.instance().getNewsList(type, pageSize, pageNo);
        }
    }

    public void getBulletinList(int subType, int pageSize, int pageNo){
        if(isConnectJni){
            GTSTerminal.instance().getBulletinList(subType, pageSize, pageNo);
        }
    }

    public void getBulletinDetail(int dataID, String language, int seq){
        if(isConnectJni){
            GTSTerminal.instance().getBulletinDetail(dataID, language, seq);
        }
    }

	public void getMobileNumber(){
        if(isConnectJni){
            GTSTerminal.instance().getMobileNumber();
        }
	}

    public void getSSOURL(int type, int seq){
        if(isConnectJni){
            GTSTerminal.instance().getSSOURL(type, seq);
        }
    }

	public void getReportSSOURL(int type, int seq, String pattern, String category){
	    if(isConnectJni){
            GTSTerminal.instance().getReportSSOURL(type, seq, pattern, category);
        }
	}

    /**设置资讯已读标志*/
    public void setNewsMarkRead(int type,String subType,int dataid){
        if(isConnectJni){
            GTSTerminal.instance().setNewsMarkRead(type,subType, dataid);
        }
    }

    /**获取资讯已读标志*/
    public boolean getNewsMarkRead(int type,String subType,int dataid){
        if(isConnectJni){
            return GTSTerminal.instance().getNewsMarkRead(type,subType, dataid);
        }

        return false;
    }
    /**获取所有资讯已读标志*/
    public void getNewsMarkReads(int type,String subType,ArrayList<Integer> mdata){
        if(isConnectJni){
            GTSTerminal.instance().getNewsMarkReads(type, subType, mdata);
        }
    }

    /**收藏资讯*/
    public void saveNewsInfo(String dataid, String data){
        if(isConnectJni){
            GTSTerminal.instance().saveNewsInfo(dataid, data);
        }
    }

    /**获取收藏的资讯*/
    public String getNewsInfo(){
        if(isConnectJni){
            return GTSTerminal.instance().getNewsInfo();
        }

        return "";
    }

    /**获取收藏的资讯的标识*/
    public boolean getNewInfo(String dataid){
        if(isConnectJni){
            return GTSTerminal.instance().getNewInfo(dataid);
        }

        return false;
    }
    /**取消收藏收藏的资讯的标识*/
    public boolean resetOneNewsInfo(String dataid){
        if(isConnectJni){
            return GTSTerminal.instance().resetOneNewsInfo(dataid);
        }

        return false;
    }


    public void requestTimeData(int zoneType, int uiCode, long time, int num, int uSeq){
        if(isConnectJni){
            GTSTerminal.instance().requestTimeData(zoneType, uiCode, time, num, uSeq);
        }
    }

    public void requestKData(GTTKDataRequest req){
        if(isConnectJni){
            GTSTerminal.instance().requestKData(req.uBourseID, req.uCodeID, req.uStartTime, req.uKLineType, req.uParam, req.nNum, req.uSeq);
        }
    }

    /**获取分时图数据*/
    public int getUptrendDataList(int uiCode, int uiDay, ArrayList<GTTTimeDataModel> mTrendList){
        if(isConnectJni){
            return GTSTerminal.instance().getUptrendDataList(uiCode, uiDay, mTrendList);
        }

        return 0;
    }

    /**
     * 获取分时最后一根线数据
     * @param uiCode
     * @param model
     * @return
     */
    public int getUptrendDataLatest(int uiCode, GTTTimeDataModel model){
        if(isConnectJni){
            return GTSTerminal.instance().getUptrendDataLatest(uiCode, model);
        }

        return 0;
    }

    /**获取K线图数据*/
    public  int getKLineDataList(int uiCodeId, int uiInterval, int uiParam, int uiCurTime, int nShNum, ArrayList<GTTKDataModel> mKLineList){
        if(isConnectJni){
            return GTSTerminal.instance().getKLineDataList(uiCodeId, uiInterval, uiParam, uiCurTime, nShNum, mKLineList);
        }

        return 0;
    }

	/**获取K线图最后一根线*/
	public int getKLineDataLatest(int uiCodeId, int uiInterval, int uiParam, GTTKDataModel model){
	    if(isConnectJni){
            return GTSTerminal.instance().getKLineDataLatest(uiCodeId, uiInterval, uiParam, model);
        }

        return 0;
	}

	/**注册接收K线最新一根线的通知*/
	public int registerKLineObersver(int uiCodeId){
		if(isConnectJni){
            return GTSTerminal.instance().registerKLineObersver(uiCodeId);
        }

        return 0;
	}

	/**解注册接收K线最新一根线的通知*/
	public int unRegisterKLineObersver(int uiCodeId){
		if(isConnectJni){
            return GTSTerminal.instance().unRegisterKLineObersver(uiCodeId);
        }

        return 0;
	}

	/**注册接收分时图最新一根线的通知*/
	public int registerUptrendObersver(int uiCodeId){
		if(isConnectJni){
            return GTSTerminal.instance().registerUptrendObersver(uiCodeId);
        }

        return 0;
	}

	/**解注册接收分时图最新一根线的通知*/
	public int unRegisterUptrendObersver(int uiCodeId){
		if(isConnectJni){
            return GTSTerminal.instance().unRegisterUptrendObersver(uiCodeId);
        }

        return 0;
	}

    /**获取K线图数据*/
    public void getKIndicatorsDataList(GTTIndexDataRequest mReq){
        if(isConnectJni){
            GTSTerminal.instance().getKIndicatorsDataList(mReq);
        }
    }

	/**异步通知获取指标数据*/
    public void asyncCalcIndicator(int uiCodeId){
        if(isConnectJni){
            GTSTerminal.instance().asyncCalcIndicator(uiCodeId);
        }
    }

	/**异步保存指标参数*/
	public void asyncSaveFormularContent(GTTFormularContent formularContent, int uiInterval){
		if(isConnectJni){
			GTSTerminal.instance().asyncSaveFormularContent(formularContent, uiInterval);
		}
	}

    /**获取指标参数*/
    public void getFormularContent(String name, GTTFormularContent formularContent, int uiInterval){
        if(isConnectJni){
            GTSTerminal.instance().getFormularContent(name, formularContent, uiInterval);
        }
    }

    /**还原指标默认值*/
    public void setFormularDefalut(String name, GTTFormularContent formularContent, int uiInterval){
        if(isConnectJni){
            GTSTerminal.instance().setFormularDefalut(name, formularContent, uiInterval);
        }
    }

    /**清除图表缓存数据，不包括DB*/
    public void clearAllChartCache(){
        if(isConnectJni){
            GTSTerminal.instance().clearAllChartCache();
        }
    }

    /**清除所有缓存数据*/
    public void ClearAllCacheData(){
        if(isConnectJni){
            GTSTerminal.instance().ClearAllCacheData();
        }
    }

    /* 设置日志存储到日志文件中的级别， 只有大于等于这个级别的日志才会被写入文件*/
    public void setLogLevel(int nLevel){
        if(isConnectJni){
            GTSTerminal.instance().setLogLevel(nLevel);
        }
    }

	/* 设置是否将日志存储到日志文件中*/
	public void setLogEnable(int nEnable){
		if(isConnectJni){
            GTSTerminal.instance().setLogEnable(nEnable);
        }
	}

    /**配置中心的通用接口*/
    public int NormalReqConfigSvr(String reqName, String jsonParam, int nSeq){
        Logger.e("配置中心的通用接口调用 reqName = " + reqName + " , jsonParam = " + jsonParam);
        if(isConnectJni){
            return GTSTerminal.instance().NormalReqConfigSvr(reqName, jsonParam, nSeq);
        }

        return 0;
    }
}
